package cc.vv.btpartyjob.partymanager.fragment

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.support.v4.widget.SwipeRefreshLayout
import android.text.TextUtils
import android.util.Log
import android.view.View
import cc.vv.baselibrary.bean.base.BaseResponseObj
import cc.vv.baselibrary.http.BaseHttpCallBack
import cc.vv.baselibrary.util.UserInfoManageUtil
import cc.vv.baselibrary.view.BTLoadMoreView
import cc.vv.btpartyjob.jnimodule.globle.BroadCastJniKey
import cc.vv.btpartyjob.partymanager.R
import cc.vv.btpartyjob.partymanager.activity.PartyPromisePingjiaListActivity
import cc.vv.btpartyjob.partymanager.adapter.UnitEvaluateAdapter
import cc.vv.btpartyjob.partymanager.api.PartyManagerAPI
import cc.vv.btpartyjob.partymanager.delegate.ManagerBaseBinder
import cc.vv.btpartyjob.partymanager.delegate.UnitEvaluateFragmentDelegate
import cc.vv.btpartyjob.partymanager.moudel.bean.CommitInfoBean
import cc.vv.btpartyjob.partymanager.moudel.req.PartyCommitedRequestObj
import cc.vv.btpartyjob.partymanager.moudel.resp.PartyCommitedNoResponseObj
import cc.vv.btpartyjob.partymanager.server.PartyManagerServer
import cc.vv.lkbasecomponent.http.LKHttp
import cc.vv.mvp.binder.BaseDataBinder
import cc.vv.mvp.fragment.BaseFragmentMVP
import com.chad.library.adapter.base.BaseQuickAdapter

/**
 * 单位承诺未评价fragment
 * Created by Chen.qi on 2018/10/29.
 */
class UnitEvaluateNoFragment : BaseFragmentMVP<UnitEvaluateFragmentDelegate>(),
        BaseQuickAdapter.OnItemClickListener,
        SwipeRefreshLayout.OnRefreshListener,
        BaseQuickAdapter.RequestLoadMoreListener {
    /**
     * 适配器
     */
    private var mAdapter: UnitEvaluateAdapter? = null

    /**
     * 当前页数
     */
    private var pageNo: Int = 1
    /**
     * 每页条数
     */
    private val pageSize: Int = 10

    private var whetherRefresh = false

    /**
     * 集合数据
     */
    private var mDataList: ArrayList<CommitInfoBean>? = null

    /**
     * 党组织Id
     */
    private var orgId: String? = null


    /**
     * 刷新数据的广播
     */
    private var mMyBroadCast: MyBroadCast? = null

    /**
     * 刷选器
     */
    private var filter: IntentFilter? = null

    /**
     * 初始化广播（接收头像和用户名改变的广播）
     */
    private fun initBroadcast() {
        if (null == mMyBroadCast) {
            mMyBroadCast = MyBroadCast()
            filter = IntentFilter()
            filter?.addAction(BroadCastJniKey.BROAD_CAST_KEY_PINGJIA)
            context.registerReceiver(mMyBroadCast, filter)
        }
    }

    /**
     * 广播接收
     */
    private inner class MyBroadCast : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent?) {
            //接收头像修改广播，发送对应的消息
            if (intent?.action == BroadCastJniKey.BROAD_CAST_KEY_PINGJIA) {
                unitCommitNoHttp("")
            }
        }
    }


    override fun initView(bundle: Bundle?) {
        super.initView(bundle)
        initBroadcast()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (null != mMyBroadCast) {
            activity?.unregisterReceiver(mMyBroadCast)
        }
    }


    override fun initData() {
        if (mAdapter == null) {
            mDataList = ArrayList()
            mAdapter = UnitEvaluateAdapter(R.layout.item_evaluate)
            viewDelegate?.setRecyclerViewAdapter(mAdapter)
            mAdapter?.setLoadMoreView(BTLoadMoreView())
            viewDelegate?.setAdapterData(mAdapter, mDataList)
        }
    }

    override fun onVisibilityChanged(visible: Boolean) {
        super.onVisibilityChanged(visible)
        if (visible && !whetherRefresh) {
            if (TextUtils.isEmpty(orgId)) {
                val userInfo = UserInfoManageUtil.getUserInfo()
                val userOrgList = userInfo?.userOrgList
                if (null != userOrgList) {
                    for (i in userOrgList.indices) {
                        if (userOrgList[i].type == 1) {
                            orgId = userOrgList[i].id
                            break
                        }
                    }
                }
            }
            PartyManagerServer.unitCommitedListNo("1", orgId, pageNo, pageSize, true)
            whetherRefresh = true
        }
    }


    override fun bindEvenListener() {
        mAdapter?.onItemClickListener = this
        viewDelegate?.bindRefreshListener(this)
        viewDelegate?.bindLoadMore(mAdapter, this)
        mAdapter?.disableLoadMoreIfNotFullPage()
    }

    override fun getDelegateClass(): Class<UnitEvaluateFragmentDelegate> {
        return UnitEvaluateFragmentDelegate::class.java
    }

    override fun getDataBinder(): BaseDataBinder<*, *> {
        return ManagerBaseBinder()
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        val intent = Intent(activity, PartyPromisePingjiaListActivity::class.java)
        intent.putExtra("id", mDataList?.get(position)?.id)
        intent.putExtra("title", "单位承诺")
        intent.putExtra("type", 1)
        startActivity(intent)
    }

    override fun getData(obj: BaseResponseObj<*>?) {
        super.getData(obj)
        if (whetherRefresh) {
            when (obj) {
                is PartyCommitedNoResponseObj -> {
                    viewDelegate?.stopRefreshing()
                    if (1 == pageNo) {
                        mDataList?.clear()
                        if (null != obj.data.records) {
                            mDataList!!.addAll(obj.data.records)
                        }
                        viewDelegate?.setAdapterData(mAdapter, mDataList)
                        mAdapter?.disableLoadMoreIfNotFullPage()
                    } else {
                        if (mAdapter?.data?.size!! >= obj.data.total) {
                            //数据全部加载完毕
                            mAdapter?.loadMoreEnd(true)
                            mAdapter?.loadMoreEnd()
                        } else {
                            //成功获取更多数据
                            if (null != obj.data.records) {
                                mDataList!!.addAll(obj.data.records)
                            }
                            mAdapter?.setNewData(mDataList)
                            //加载数据
                            mAdapter?.disableLoadMoreIfNotFullPage()
                            mAdapter?.loadMoreComplete()
                        }
                    }
                }
            }
        }

    }

    override fun getBadCode(obj: BaseResponseObj<*>?) {
        super.getBadCode(obj)
        if (1 == pageNo) {
            viewDelegate?.stopRefreshing()
        }
        mAdapter?.loadMoreComplete()
        mAdapter?.loadMoreFail()
    }

    override fun onHttpFailure(url: String?, exceptionStr: String?) {
        super.onHttpFailure(url, exceptionStr)
        if (1 == pageNo) {
            viewDelegate?.stopRefreshing()
        }
    }

    override fun onRefresh() {
        mAdapter?.setEnableLoadMore(false)//这里的作用是防止下拉刷新的时候还可以上拉加载
        pageNo = 1
        PartyManagerServer.unitCommitedListNo("1", orgId, pageNo, pageSize, false)

    }

    override fun onLoadMoreRequested() {
        if (mDataList!!.size < 10) {
            mAdapter?.loadMoreComplete()
            mAdapter?.loadMoreEnd(true)
            return
        }
        pageNo++
        PartyManagerServer.unitCommitedListNo("1", orgId, pageNo, pageSize, false)
    }


    /**
     * 组织选择后(未评价)
     */
    fun unitCommitNoHttp(id: String?) {
        if (!TextUtils.isEmpty(id)) {
            orgId = id
        }
        pageNo = 1
        val request = PartyCommitedRequestObj()
        request.havingComment = "1"
        request.orgId = orgId
        request.page = "$pageNo"
        request.pageSize = "$pageSize"
        LKHttp.get(PartyManagerAPI.unitCommitmentListUrl, request, PartyCommitedNoResponseObj::class.java,
                object : BaseHttpCallBack<PartyCommitedNoResponseObj>() {
                    override fun onSuccess(url: String?, obj: PartyCommitedNoResponseObj?) {
                        super.onSuccess(url, obj)
                        if (1 == pageNo) {
                            mDataList?.clear()
                            if (null != obj?.data?.records) {
                                mDataList!!.addAll(obj.data.records)
                            }
                            Log.e("lk_chen", "result看啊看==" + mDataList!!.size);
                            viewDelegate?.setAdapterData(mAdapter, mDataList)
                            mAdapter?.disableLoadMoreIfNotFullPage()
                        }
                    }

                }, false)
    }

}